<template>
  <div>
    <!-- 表单 -->
    <div class="from_post el_radio_let">
      <el-form label-width="180px" :model="fromData" :rules="rules" ref="ruleForm">
        <el-form-item label="封面" class="requ">
          <div class="imgpost">
            <el-upload class="avatar-uploader" name="production" ref="upload" :action="$upUrl" :show-file-list="false" :auto-upload="false" :before-upload="beforeAvatarUpload" :on-change="changimg" accept=".jpg,.png,.jpeg">
              <div class="upimg" style="height:100px;width:100px" v-if="imageUrl" @click.stop="">
                <img :src="imageUrl" class="avatar" />
                <div>
                  <div>
                    <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview(imageUrl)"></i>
                  </div>
                  <div>
                    <i class="el-icon-delete" @click.stop="handleRemove"></i>
                  </div>
                </div>
              </div>
              <div v-else style="height:100px;width:100px" class="upback">
                <div>
                  <i class="el-icon-plus elimg_icon"></i>
                  <div class="elimg_text">添加封面</div>
                </div>
              </div>
            </el-upload>
            <div class="img_ps">
              支持jpg、jpeg、png图片，大小请控制在2M以内。
            </div>
          </div>

          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="imageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="名称" prop="gather_name">
          <el-input v-model="fromData.gather_name" placeholder="请输入名称"></el-input>
        </el-form-item>

        <el-form-item label="上传视频" class="requ">
          <div class="imgpost">
            <el-upload class="avatar-uploader" name="product" ref="upload" :action="$upUrl" :show-file-list="false" :auto-upload="false" :on-change="uploadMp4" accept=".mp4">
              <div class="video_box" style="height: 400px; width: 600px" v-if="videoBase64" @click.stop="">
                <el-tooltip content="点击删除上传的视频" placement="top">
                  <div class="video_del">
                    <i class="el-icon-delete" @click.stop="videoBase64 = ''"></i>
                  </div>
                </el-tooltip>
                <video controls v-if="videoBase64" style="height: 400px; width: 600px">
                  <source :src="videoBase64" type="video/mp4" />
                </video>
              </div>
              <div v-else class="upback">
                <div>
                  <i class="el-icon-plus elimg_icon"></i>
                </div>
              </div>
            </el-upload>
          </div>
          <div class="img_ps">支持mp4，大小控制在200M以内，上传的视频不会对源视频做水印处理，若需水印，需线下处理在进行上传</div>
        </el-form-item>

        <el-form-item>
          <div style="padding: 48px 0 48px 0" class="btn_el">
            <el-button @click="submitForm('ruleForm')" class="btn_establish">
              提交
            </el-button>
            <el-button class="btn_cancel" @click="can">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- vueCropper 剪裁图片实现-->
    <x-cropperFixed ref="iscropper" :uploadImg="uploadImgs" @cropPicture="cropPicture" :cropImg="cropImgOne"></x-cropperFixed>
  </div>
</template>

<script>
import vmEditor from "@/components/editor/editor.vue";
export default {
  components: {
    vmEditor,
  },
  props: {
    type: { type: String, default: "add" },
    fromData: {
      type: Object,
      default() {
        return {};
      },
    },
    cropImgOne: {
      type: String,
      default: true,
    },
    cropImg: {
      type: String,
      default: true,
    },
  },
  data() {
    const validatePass = (rule, value, callback) => {
      console.log(
        this.fromData,
        this.fromData.start_time == "",
        this.fromData.end_time == "",
        this.fromData.end_time,
        this.fromData.start_time
      );
      if (
        this.fromData.start_time == "" ||
        this.fromData.end_time == "" ||
        this.fromData.start_time == null ||
        this.fromData.end_time == null
      ) {
        callback(new Error("请输入开放时间"));
      } else {
        callback();
      }
    };

    return {
      videoBase64: '',
      unimgurl: "",
      uploadShare: "",
      dialogpngTwo: false,
      uploadImgs: "",
      dialogVisible: false,
      imageUrl: "",
      headCavityList: [],
      levelList: [],
      typeList: [],
      videoFile: null,
      rules: {
        gather_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        author: [
          { required: true, message: "请输入作者", trigger: "blur" },
        ],
        intro: [
          { required: true, message: "请输入简介", trigger: "blur" },
        ],

      },
    };
  },
  computed: {},

  activated() {
    this.imageUrl = this.fromData.img;
    this.videoBase64 = ''
  },
  watch: {
    fromData: {
      // 修改时部分数据回溯
      handler(val, oldVal) {
        // 监听外部的图片是否请求完毕
        if (val.img != oldVal.img) {
          this.imageUrl = this.$img(this.fromData.img);
        }
        if (this.fromData.gather_src) {
          this.videoBase64 = this.$img(this.fromData.gather_src)
        }

      },
      deep: true, //true 深度监听
    },
    // 要剪裁图片
    uploadImgs(nal, al) {
      this.uploadImgs = nal;
    },
  },
  mounted() {
    this.getTypeList()
  },
  methods: {
    _upoloadMP4(file = '') {
      let that = this
      if (!file) {
        return
      }
      return new Promise((resolve) => {
        this.request({
          url: "/uploads/files",
          method: "post",
          dataType: "blob",
          loading: true,
          data: {
            temp_video: file,
          },
        }).then((res) => {
          that.fromData.gather_src = res.content.img
          that.fromData.size = res.content.file_size
          resolve(1)
        }).catch(e => this.errorHandler(e))
      })
    },
    // 视频转换为base64Url
    uploadMp4(file) {
      this.videoFile = file.raw
      let reader = new FileReader()
      let that = this
      let refile
      reader.readAsDataURL(file.raw)
      reader.onload = (e) => {
        that.videoBase64 = e.target.result //result是你读取到的文件内容，此属性读取完成才能使用
        // refile = that.base64UrlToFile(dataBase64,'a.mp4')
        // that.videoBase64 = URL.createObjectURL(refile)
      }
      // this._upoloadMP4(file.raw);
    },
    getTypeList() {
      this.request({ url: 'admin/resourceTotalType/filterList' }).then(res => {
        this.typeList = res.content
      }).catch(e => this.errorHandler(e))
    },

    handleRemove() {
      (this.imageUrl = ""), (this.unimgurl = "");
    },
    //选择图片查看详情
    handlePictureCardPreview(img) {
      this.imageUrl = img;
      this.dialogVisible = true;
    },
    // 上传图片
    uploadImg(fileUrl, param) {
      return new Promise(async (reslove) => {
        try {
          if (fileUrl) {
            let imgRes = await this.request({
              url: "/uploads/files",
              method: "post",
              dataType: "blob",
              loading: true,
              data: {
                img: fileUrl,
              },
            });
            if (imgRes) {
              reslove(imgRes.content.img);
            }
          } else {
            reslove(this.fromData.img);
          }
        } catch (err) {
          this.errorHandler(err);
        }
      });
    },

    // 裁剪返回参数
    cropPicture(imgUrl) {
      this.unimgurl = imgUrl.file;
      this.imageUrl = imgUrl.dataURL;
    },
    // 上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpg" || "image/png" || "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 <= 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、png、jpeg 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 图片处理
    changimg(file) {
      const isLt2M = file.size / 1024 / 1024 <= 1;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      } else {
        let that = this;
        const fr = new FileReader();
        fr.readAsDataURL(file.raw);
        fr.onload = function () {
          // console.log(fr.result);
          return (that.uploadImgs = fr.result);
        };
        setTimeout(() => {
          this.$refs.iscropper.showModal({
            cutWidth: 245, // 默认生成截图框宽度
            cutHeight: 245, // 默认生成截图框高度
            rate: "1",
            file: file.raw,
          });
        }, 100);
      }
    },

    // 提交
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!this.videoBase64) {
          this.$message.warning('请上传视频')
          return
        }
        if (!this.imageUrl) {
          this.$message.warning('请上传封面')
          return
        }

        await this._upoloadMP4(this.videoFile)
        this.fromData.img = await this.uploadImg(this.unimgurl, "img")


        if (valid) {
          this.$emit("btn_submit", this.fromData);
        }
      });
    },

    //返回上一页
    can() {
      if (this.$route.query.action) {
        this.$delete(this.$route.query, "action");
      }
      this.pageTurn('/videoManageList/resourceList?', { id: this.$route.query.id })
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
.plus {
  width: 90px;
  height: 90px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #999999;
}
.video_box {
  position: relative;
  video {
    z-index: 9;
  }
  .video_del {
    position: absolute !important;
    z-index: 100;
    top: 0px;
    right: 0;
    color: #fff;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #df5146;
  }
}
</style>

